package com.yjhb.android.sbz.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.entity.CheckResult;
import com.yjhb.android.sbz.entity.TaskOrder;
import com.yjhb.android.sbz.entity.TaskStep;
import com.yjhb.android.sbz.entity.TaskSubmit;
import com.yjhb.android.sbz.enums.TaskStatus;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.view.TaskStepView;
import com.jojo.android.zxlib.base.BaseRecyclerAdapterV2;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxTimeTool;
import com.jojo.android.zxlib.view.CircleImageView;
import com.jojo.android.zxlib.view.EmptyRecyclerView;
import com.jojo.android.zxlib.view.EmptyView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建者 zx
 * 创建时间 2020/12/16 9:31
 */
public class CheckViewPagerAdapter extends PagerAdapter {
    private final String TAG = "CheckViewPagerAdapter";

    private Context context;
    private List<CheckResult> checkResults;
    private Map<Integer, List<TaskOrder>> taskOrders = new HashMap<>();
    private Map<Integer, View> cache = new HashMap<>();

    public CheckViewPagerAdapter(Context context, List<CheckResult> checkResults) {
        this.context = context;
        this.checkResults = checkResults;
    }


    public void putTaskOrder(int index, List<TaskOrder> taskOrder) {
        taskOrders.put(index, taskOrder);
        View view = cache.get(index);
        if (view != null) {
            instantiateItem((ViewGroup) view.getRootView(), index);
        }
    }

    @Override
    public int getCount() {
        if (checkResults == null) return 0;
        return checkResults.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = cache.get(position);
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.layout_task_check, container, false);
            container.addView(view);
            cache.put(position, view);
        }
        CircleImageView headIv = view.findViewById(R.id.head_iv);
        TextView contactTv = view.findViewById(R.id.contact_tv);
        TextView taskTitleTv = view.findViewById(R.id.task_title_tv);
        TextView submitUserIdTv = view.findViewById(R.id.submit_user_id_tv);
        TextView submit_user_nickname_tv = view.findViewById(R.id.submit_user_nickname_tv);
        TextView signDateTv = view.findViewById(R.id.sign_date_tv);
        TextView submitDateTv = view.findViewById(R.id.submit_date_tv);
        TextView checkDateTv = view.findViewById(R.id.check_date_tv);
        TaskStepView taskStepView = view.findViewById(R.id.task_step_view);
        EmptyView emptyView = view.findViewById(R.id.emptyView);
        EmptyRecyclerView emptyRecyclerView = view.findViewById(R.id.emptyRecyclerView);
        CheckResult checkResult = checkResults.get(position);
        Glide.with(context).load(checkResult.getAvatar()).apply(new RequestOptions().placeholder(R.mipmap.test_head)).into(headIv);
        taskTitleTv.setText(checkResult.getTitle());
        submitUserIdTv.setText("用户ID:" + checkResult.getTaskOrder().getUserId());
        submit_user_nickname_tv.setText("用户昵称:" + (checkResult.getNickName() == null ? "" : checkResult.getNickName()));
        signDateTv.setText("报名时间:" + ZxTimeTool.getTimeStr(checkResult.getTaskOrder().getFetchDateTime()));
        submitDateTv.setText("提交时间:" + ZxTimeTool.getTimeStr(checkResult.getTaskOrder().getSubmitDateTime()));
        switch (TaskStatus.getStatus(checkResult.getTaskOrder().getState())) {
            case TASK_STATUS_SUBMIT:
                contactTv.setVisibility(View.VISIBLE);
                break;
            case TASK_STATUS_FAIL:
                if (checkResult.getTaskOrder().getAuditDateTime() == null ||
                        System.currentTimeMillis() - checkResult.getTaskOrder()
                                .getAuditDateTime().getTime() < 1000 * 60 * 60 * 24) {
                    contactTv.setVisibility(View.VISIBLE);
                } else {
                    contactTv.setVisibility(View.GONE);
                }
                break;
            default:
                contactTv.setVisibility(View.GONE);
        }
        contactTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tool.startChatActivity(context, "" + checkResult.getTaskOrder().getUserId(), checkResult.getNickName(), 2);
            }
        });
        try {
            //设置步骤
            List<TaskStep> taskSteps = new ArrayList<>();
            List<TaskSubmit> submits = new Gson().fromJson(checkResult.getTaskOrder().getContent(),
                    new TypeToken<List<TaskSubmit>>() {
                    }.getType());
            if (submits != null) {
                for (int i = 0; i < submits.size(); i++) {
                    TaskStep step = new TaskStep();
                    step.setSort(i);
                    step.setContent(submits.get(i).getContent());
                    step.setTitle(submits.get(i).getTitle());
                    step.setType(submits.get(i).isImg() ? 3 : 5);
                    taskSteps.add(step);
                }
            }
            taskStepView.setTask(taskSteps);
            taskStepView.setCheck(true);
            taskStepView.refresh();
            taskStepView.setEnabled(true);
            taskStepView.setSign(true);
            //设置历史记录
            emptyRecyclerView.setEmptyView(emptyView);
            List<TaskOrder> taskOrder = taskOrders.get(position);
            if (taskOrder != null && taskOrder.size() > 0) {
                HisOrderAdapter hisOrderAdapter = new HisOrderAdapter(context);
                hisOrderAdapter.setCheckResult(checkResult);
                hisOrderAdapter.setData(taskOrder);
                emptyRecyclerView.setAdapter(hisOrderAdapter);
            } else {
                emptyView.getEmptyTipsTv().setTextColor(Color.parseColor("#dcdcdc"));
                emptyView.getEmptyTipsTv().setTextSize(12);
                emptyView.showTips("暂无历史记录");
            }

        } catch (Exception e) {
            ZxLogTool.err(e);
        }
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
        taskOrders.remove(position);
        cache.remove(position);
    }


    private class HisOrderAdapter extends BaseRecyclerAdapterV2<BaseRecyclerAdapterV2.BaseHolder, TaskOrder> {
        private CheckResult checkResult;

        public HisOrderAdapter(Context context) {
            super(context);
        }

        public void setCheckResult(CheckResult checkResult) {
            this.checkResult = checkResult;
        }


        @Override
        protected BaseHolder getHolder(View v) {
            return new BaseHolder(v);
        }

        @Override
        protected int getLayoutId() {
            return R.layout.item_task_history_order;
        }

        @Override
        public void onBindViewHolder(@NonNull BaseHolder holder, int position) {
            CircleImageView circleImageView = holder.findViewById(R.id.head_iv);
            Glide.with(context).load(checkResult.getAvatar())
                    .error(R.mipmap.test_head)
                    .into(circleImageView);
            TextView textView = holder.findViewById(R.id.nickname_tv);
            textView.setText(new StringBuilder(checkResult.getNickName() == null ? "" : checkResult.getNickName())
                    .append("(ID:")
                    .append(checkResult.getTaskOrder().getUserId())
                    .append(")")
            );
            TextView timeTv = holder.findViewById(R.id.time_tv);
            timeTv.setText("报名时间：" + ZxTimeTool.getTimeStr(data.get(position).getFetchDateTime()));
            TextView stateTv = holder.findViewById(R.id.state_tv);
            stateTv.setText(TaskStatus.getStatus(entity.getState()).getStatusStr());

        }
    }


}
